package main

import (
	"net/http"
	_ "pop3api/docs"

	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

// ErrorHandler captures errors and returns a consistent JSON error response
func ErrorHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next() // Step1: Process the request first.

		// Step2: Check if any errors were added to the context
		if len(c.Errors) > 0 {
			// Step3: Use the last error
			err := c.Errors.Last().Err

			// Step4: Respond with a generic error message
			c.JSON(http.StatusInternalServerError, map[string]any{
				"success": false,
				"message": err.Error(),
			})
		}

		// Any other steps if no errors are found
	}
}

// @title Pop3 API
// @version 1.0
// @description Pop3 服务 API 文档
// @BasePath /
func main() {
	r := gin.Default()
	r.Use(gzip.Gzip(gzip.DefaultCompression))

	// Attach the error-handling middleware
	r.Use(ErrorHandler())

	// 注册服务
	inboxPoolService := NewInboxPoolServiceWithBackground()

	// 注册你的路由
	// 假设你已经有 inboxPoolService 的初始化
	RegisterEmailRouter(r, inboxPoolService)

	// Swagger UI 路由（访问: http://localhost:9000/swagger/index.html）
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	_ = r.Run(":9000")
}
